package com.cxhc.system.service.hcdoc.impl;

import com.cxhc.common.utils.DateUtils;
import com.cxhc.common.utils.StringUtils;
import com.cxhc.system.domain.hcdoc.HdApprovalForm;
import com.cxhc.system.domain.hcdoc.HdBranchBudget;
import com.cxhc.system.domain.hcdoc.HdBranchInfo;
import com.cxhc.system.domain.hcdoc.HdProjectDocInfo;
import com.cxhc.system.domain.hcdoc.HdProjectInfo;
import com.cxhc.system.mapper.hcdoc.HdApprovalFormMapper;
import com.cxhc.system.mapper.hcdoc.HdBranchBudgetMapper;
import com.cxhc.system.mapper.hcdoc.HdBranchInfoMapper;
import com.cxhc.system.mapper.hcdoc.HdProjectDocInfoMapper;
import com.cxhc.system.mapper.hcdoc.HdProjectInfoMapper;
import com.cxhc.system.service.hcdoc.HdBranchInfoService;
import com.cxhc.system.service.hcdoc.HdProjectInfoService;
import org.apache.poi.hssf.record.DVALRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;


@Service
public class HdProjectInfoServiceImpl implements HdProjectInfoService {

    @Autowired
    private HdProjectInfoMapper hdProjectInfoMapper;

    @Autowired
    private HdBranchBudgetMapper hdBranchBudgetMapper;

    @Autowired
    private HdBranchInfoMapper hdBranchInfoMapper;

    @Autowired
    private HdProjectDocInfoMapper hdProjectDocInfoMapper;

    @Autowired
    private HdApprovalFormMapper hdApprovalFormMapper;


    @Override
    public HdProjectInfo selectById(String id) {
        HdProjectInfo hdProjectInfo = hdProjectInfoMapper.selectById(id);
        List<HdProjectDocInfo> hdProjectDocInfos = hdProjectDocInfoMapper.selectListByProjectId(id);
        if (!StringUtils.isEmpty(hdProjectInfo.getNowPayNode())){
            hdProjectInfo.setIsChange("0");
        }else {
            hdProjectInfo.setIsChange("1");
        }
        hdProjectInfo.setHdProjectDocInfos(hdProjectDocInfos);
        return hdProjectInfo;
    }

    @Override
    public int insertHdProjectInfo(HdProjectInfo hdProjectInfo) {

        HdBranchInfo hdBranchInfo = hdBranchInfoMapper.selectById(hdProjectInfo.getBranchInfoId());
        //获取项目id
        String timeString = String.valueOf(System.currentTimeMillis());
        String dateStr = DateUtils.parseDateToStr(DateUtils.YYYYMMDD, new Date());
        String id = "HC_" + hdBranchInfo.getBranchShortName() + "_" + dateStr + "_" + timeString.substring(timeString.length()-3);
        hdProjectInfo.setProjectSerialNo(id);
        BigDecimal contractAmount = new BigDecimal(hdProjectInfo.getContractAmount().replaceAll(",",""));
        String branchInfoId = hdProjectInfo.getBranchInfoId();
        changeBranchBudget(branchInfoId,dateStr.substring(0,4),contractAmount);
        //新增文档信息
        List<HdProjectDocInfo> hdProjectDocInfos = hdProjectInfo.getHdProjectDocInfos();
        int insert = hdProjectInfoMapper.insert(hdProjectInfo);
        if (1 == insert && !CollectionUtils.isEmpty(hdProjectDocInfos)){
            HdProjectInfo hdProjectInfoNew = hdProjectInfoMapper.selectByProjectNo(id);
            for (HdProjectDocInfo hdProjectDocInfo : hdProjectDocInfos) {
                hdProjectDocInfo.setProjectInfoId(String.valueOf(hdProjectInfoNew.getId()));
            }
            hdProjectDocInfoMapper.batchInsertDoc(hdProjectDocInfos);
        }
        return insert;
    }

    public void changeBranchBudget(String branchInfoId,String year,BigDecimal contractAmount){
        HdBranchBudget hdBranchBudget = hdBranchBudgetMapper.selectByBranchInfoIdAndYear(branchInfoId,year);
        synchronized (hdBranchBudget.getId()){
            BigDecimal availableAmount = new BigDecimal(hdBranchBudget.getAvailableAmount().replaceAll(",",""));
            BigDecimal transferredAmoun = new BigDecimal(hdBranchBudget.getTransferredAmount().replaceAll(",",""));
//            if (availableAmount.compareTo(contractAmount) < 0){
//                throw new RuntimeException("项目金额超出部门剩余可用预算金额!!!");
//            }
            HdBranchBudget hdBranchBudgetUpdate = new HdBranchBudget();
            hdBranchBudgetUpdate.setId(hdBranchBudget.getId());
            hdBranchBudgetUpdate.setAvailableAmount(String.valueOf(availableAmount.subtract(contractAmount)));
            hdBranchBudgetUpdate.setTransferredAmount(String.valueOf(transferredAmoun.add(contractAmount)));
            hdBranchBudgetMapper.update(hdBranchBudgetUpdate);
        }

    }

    @Override
    public List<HdProjectInfo> selectList(HdProjectInfo hdProjectInfo) {
        return hdProjectInfoMapper.selectList(hdProjectInfo);
    }

    @Override
    public int update(HdProjectInfo hdProjectInfo) {
        HdProjectInfo hdProjectInfoTemp = hdProjectInfoMapper.selectById(String.valueOf(hdProjectInfo.getId()));
        if ("1".equals(hdProjectInfoTemp.getStat())){
            throw new RuntimeException("当前项目已存档不可更改!!!");
        }
        if (!StringUtils.isEmpty(hdProjectInfoTemp.getNowPayNode())){
            if (!hdProjectInfoTemp.getPayType().equals(hdProjectInfo.getPayType())
                    || (hdProjectInfoTemp.getPayDates() != null && !hdProjectInfoTemp.getPayDates().equals(hdProjectInfo.getPayDates()))
                        || !hdProjectInfoTemp.getContractAmount().equals(hdProjectInfo.getContractAmount())){
                throw new RuntimeException("当前项目已支付,项目支付方式、支付节点、合同金额不可更改!!!");
            }
        }
        List<HdApprovalForm> hdApprovalForms = hdApprovalFormMapper.selectListByProjectId(String.valueOf(hdProjectInfo.getId()));
        if (!CollectionUtils.isEmpty(hdApprovalForms)){
            throw new RuntimeException("该项目存在审批中记录,请审批后重试!!!");
        }

        BigDecimal contractAmountTemp = new BigDecimal(hdProjectInfoTemp.getContractAmount().replaceAll(",",""));
        BigDecimal contractAmount = new BigDecimal(hdProjectInfo.getContractAmount().replaceAll(",",""));
        //变更项目金额大于原项目金额 进行预算部门金额校验
        if(contractAmountTemp.compareTo(contractAmount) < 0){
            HdBranchBudget hdBranchBudget = hdBranchBudgetMapper.selectByBranchInfoIdAndYear(hdProjectInfoTemp.getBranchInfoId(),hdProjectInfoTemp.getCtime().substring(0,4));
            //增加金额
            BigDecimal subtract = contractAmount.subtract(contractAmountTemp);
            synchronized (hdBranchBudget.getId()){
                BigDecimal availableAmount = new BigDecimal(hdBranchBudget.getAvailableAmount().replaceAll(",",""));
                BigDecimal transferredAmoun = new BigDecimal(hdBranchBudget.getTransferredAmount().replaceAll(",",""));
//                if (availableAmount.compareTo(subtract) < 0){
//                    throw new RuntimeException("项目金额超出部门剩余可用预算金额!!!");
//                }
                HdBranchBudget hdBranchBudgetUpdate = new HdBranchBudget();
                hdBranchBudgetUpdate.setId(hdBranchBudget.getId());
                hdBranchBudgetUpdate.setAvailableAmount(String.valueOf(availableAmount.subtract(subtract)));
                hdBranchBudgetUpdate.setTransferredAmount(String.valueOf(transferredAmoun.add(subtract)));
                hdBranchBudgetMapper.update(hdBranchBudgetUpdate);
            }
        }
        //变更项目金额小于原项目金额无需校验部门预算直接进行变更
        if(contractAmountTemp.compareTo(contractAmount) > 0){
            HdBranchBudget hdBranchBudget = hdBranchBudgetMapper.selectByBranchInfoIdAndYear(hdProjectInfoTemp.getBranchInfoId(),hdProjectInfoTemp.getCtime().substring(0,4));
            //增加金额
            BigDecimal subtract = contractAmountTemp.subtract(contractAmount);
            synchronized (hdBranchBudget.getId()){
                BigDecimal availableAmount = new BigDecimal(hdBranchBudget.getAvailableAmount().replaceAll(",",""));
                BigDecimal transferredAmoun = new BigDecimal(hdBranchBudget.getTransferredAmount().replaceAll(",",""));
                HdBranchBudget hdBranchBudgetUpdate = new HdBranchBudget();
                hdBranchBudgetUpdate.setId(hdBranchBudget.getId());
                hdBranchBudgetUpdate.setAvailableAmount(String.valueOf(availableAmount.add(subtract)));
                hdBranchBudgetUpdate.setTransferredAmount(String.valueOf(transferredAmoun.subtract(subtract)));
                hdBranchBudgetMapper.update(hdBranchBudgetUpdate);
            }
        }

        //更改项目文档
        return hdProjectInfoMapper.update(hdProjectInfo);
    }

    @Override
    public int delete(String id) {
        //校验是否可删除
        HdProjectInfo hdProjectInfo = hdProjectInfoMapper.selectById(id);
        if ("1".equals(hdProjectInfo.getStat())){
            throw new RuntimeException("当前项目已存档,不可删除!!!");
        }
        if (!StringUtils.isEmpty(hdProjectInfo.getNowPayNode())){
            throw new RuntimeException("当前项目已支付,不可删除!!!");
        }
        List<HdApprovalForm> hdApprovalForms = hdApprovalFormMapper.selectListByProjectId(String.valueOf(hdProjectInfo.getId()));
        if (!CollectionUtils.isEmpty(hdApprovalForms)){
            throw new RuntimeException("该项目存在审批中记录,请审批后重试!!!");
        }
        HdBranchBudget hdBranchBudget = hdBranchBudgetMapper.selectByBranchInfoIdAndYear(hdProjectInfo.getBranchInfoId(),hdProjectInfo.getCtime().substring(0,4));
        BigDecimal availableAmount = new BigDecimal(hdBranchBudget.getAvailableAmount().replaceAll(",",""));
        BigDecimal transferredAmoun = new BigDecimal(hdBranchBudget.getTransferredAmount().replaceAll(",",""));
        BigDecimal contractAmount = new BigDecimal(hdProjectInfo.getContractAmount().replaceAll(",",""));

        HdBranchBudget hdBranchBudgetUpdate = new HdBranchBudget();
        hdBranchBudgetUpdate.setId(hdBranchBudget.getId());
        hdBranchBudgetUpdate.setAvailableAmount(String.valueOf(availableAmount.add(contractAmount)));
        hdBranchBudgetUpdate.setTransferredAmount(String.valueOf(transferredAmoun.subtract(contractAmount)));
        hdBranchBudgetMapper.update(hdBranchBudgetUpdate);
        //删除后进行部门预选扣减


        return hdProjectInfoMapper.deleteById(id);
    }
}
